package com.jdk.demo.fileChannel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelTest {

	public static void main(String[] args) throws Exception {
		File file = new File("E:/zsl/temp2.txt");
		File bak = new File("E:/zsl/temp3.txt");
		FileInputStream fileInputStream = new FileInputStream(file);
		FileOutputStream bakOutputStream = new FileOutputStream(bak);
		FileChannel fileChannel = fileInputStream.getChannel();
		FileChannel bakChannel = bakOutputStream.getChannel();

		ByteBuffer buffer = ByteBuffer.allocate(10);

		while (true) {
			/**
			 * 如果不调用clear方法，buffer的position和limit的位置是一样的，
			 * 这样会导致fileChannel的read方法会返回0，不仅文件中的其他内容无法写入buffer,
			 * 源码细节（https://blog.csdn.net/u013828625/article/details/79699743）
			 * 而且当前应用就会进入死循环
			 */
			buffer.clear();
			int sta = fileChannel.read(buffer);
			if (sta == -1) {
				break;
			}
			/**
			 * 一定要记得调用flip方法，调整limit=position,positon=0,这样才能将buffer中的数据拿出来
			 */
			buffer.flip();
			bakChannel.write(buffer);
		}
		bakChannel.force(false);
		fileChannel.close();
		bakChannel.close();
	}

}
